package com.waves.web;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.wangbo.test.util.JacksonUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

public class TestMultipartFile {

    public static final String IP = "120.92.137.180";
    public static final int PORT = 8080;
    public static final String USERNAME = "wangbo";
    public static final String PASSWORD = "123456";

    public static final String URL_PATTERN = "http://%s:%d/service/api/%s";
    public static final String CHECK_QUALITY = "checkquality";
    public static final String LOGIN = "user/login";

    public static void main(String[] args) {


//        RestTemplate restTemplate = new RestTemplateBuilder().errorHandler(new DefaultResponseErrorHandler(){
//            /**
//             * 设置RestTemplate自带的异常处理器不做异常处理
//             **/
//            @Override
//            public void handleError(ClientHttpResponse response) {
//            }
//        }).build();
//
//        String token = login(restTemplate);
//
//        boolean ok = checkQuality(restTemplate, token, bytes);
//        System.out.printf("图片质量结果：%b", ok);


    }

    /**
     * 传输文件压缩后转字节数组
     * MultipartFile -> Image -> byte[]
     */
    @Test
    @SneakyThrows
    public static byte[] test01() {
        MockMultipartFile multipartFile = new MockMultipartFile("test.jpg", FileUtil.readBytes("D:\\temp\\test.jpg"));
        BufferedImage image1 = ImgUtil.read(multipartFile.getInputStream());
        int max = Math.max(image1.getHeight(),image1.getWidth());
        Image image2 = ImgUtil.scale(image1, (float) 1000 / max);
        @Cleanup
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImgUtil.write(image2, "jpg", bos);
        return bos.toByteArray();
    }

    /**
     * 登录
     **/
    private static String login(RestTemplate restTemplate) {
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("username",USERNAME);
        param.add("password", Base64.getEncoder().encode(PASSWORD.getBytes(UTF_8)));

        String url = String.format(URL_PATTERN, IP, PORT, LOGIN);
        String result = restTemplate.postForObject(url, param, String.class);
        return result;
    }

    /**
     * 检查图片质量
     **/
    private static boolean checkQuality(RestTemplate restTemplate, String token, byte[] bytes) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", token);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        String url = String.format(URL_PATTERN, IP, PORT, CHECK_QUALITY);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        String str = Base64.getEncoder().encodeToString(bytes);
        param.add("image-data", "data:image/jpeg;base64," + str);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        Map map = JacksonUtil.toMap(result);
        boolean pass = "pass".equals(map.get("result"));
        return pass;

    }

    /**
     * 字节数组转传输文件
     * byte[] -> MultipartFile
     */
    public static void test02(byte[] bytes, RestTemplate restTemplate) {
        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return "xxx.jpg";
            }
        };

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("multipartFile ",byteArrayResource);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject("http://120.92.141.239:8080/aiSchool/sys/media", httpEntity, String.class);
        System.out.println(result);

    }
}
